from . import passport_blue
from flask import request,jsonify,current_app,make_response,session,g
from info.utils.response_code import RET
from info.models import User
from info.utils.captcha.captcha import captcha
from info import redis_store,db
import re,random
from info.libs.yuntongxun.sms import CCP
from info.utils.comments import login_required


#生成图片验证码
@passport_blue.route('/imagecode')
def image_code():

    image_code = request.args.get('cur')
    if not image_code:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        name,text,image = captcha.generate_captcha()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='生成验证码失败')
    print('图片码：',text)
    try:
        redis_store.setex('imagecode_'+image_code,300,text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='存储验证码失败')

    resp = make_response(image)
    resp.headers['contentType']='image/jpg'
    return resp

#验证图片验证码，生成随机码并发送给用户
@passport_blue.route('/smscode',methods=['POST'])
def smscode():

    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')

    if not re.match(r'1[3456789]\d{9}$',mobile):
        return jsonify(errno=RET.DATAERR,errmsg='请输入正确手机号')

    try:
        real_image_code = redis_store.get('imagecode_'+image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='读取验证信息失败')
    try:
       redis_store.delete('imagecode_'+image_code_id)
    except Exception as e:
        current_app.logger.error(e)

    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg='验证码错误')

    #判断用户是否存在
    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='读取用户数据失败')
    if user:
        return jsonify(errno=RET.DATAEXIST,errmsg='用户已注册')

    #生成随机验证码
    text_code = '%06d'%random.randint(0,999999)
    print(text_code)

    try:
        redis_store.setex('smscode_'+mobile,300,text_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='存储随机码失败')

    try:

        ret = CCP().send_template_sms(mobile,[text_code,5],1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='网络异常')

    if ret:
        return jsonify(errno=RET.THIRDERR, errmsg='信息发送失败')
    else:
        return jsonify(errno=RET.OK, errmsg='信息发送成功')

#获得短信验证码后开始注册
@passport_blue.route('/register',methods=['POST'])
def user():

    mobile = request.json.get('mobile')
    smscode = request.json.get('phonecode')
    password = request.json.get('password')

    if not all([mobile,smscode,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        real_smscode=redis_store.get('smscode_'+mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='读取信息失败')

    if int(smscode) != int(real_smscode):
        return jsonify(errno=RET.DATAERR, errmsg='验证码错误')

    user = User()
    user.mobile = mobile
    user.password = password
    user.name = mobile

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='存储用户信息失败')

    try:
        redis_store.delete('smscode_'+mobile)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK,errmsg='注册成功,请登陆！')

@passport_blue.route('/session',methods=['GET','POST','DELETE'])
@login_required
def fnSession():

    if request.method=='DELETE':
        # redis_store.delete('user_id')
        session.pop('user_id', None)
        return jsonify(errno=RET.OK,errmsg='OK')

    if request.method=='GET':
        user = g.user
        data = {
            'name':user.name,
            'user_id':user.id
        } if user else  None
        return jsonify(errno=RET.OK,errmsg='OK',data=data)

    if request.method =='POST':

        mobile = request.json.get('mobile')
        password = request.json.get('password')

        if not all([mobile,password]):
            return jsonify(errno=RET.PARAMERR,errmsg='登陆参数缺失')

        if not re.match(r'1[3456789]\d{9}$',mobile):
            return jsonify(errno=RET.DATAERR,errmsg='请输入正确手机号')

        try:
            user = User.query.filter(User.mobile==mobile).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='读取用户数据失败')

        if not user or not user.check_passowrd(password):
            return jsonify(errno=RET.NODATA,errmsg='用户名或密码输入错误')

        session['user_id'] = user.id
        return jsonify(errno=RET.OK,errmsg="登陆成功")
